<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { DressResourceApi } from '#/api/wedding/dressresource';

import { Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';

import { Image, message, QRCode } from 'ant-design-vue';

import { $t } from '#/locales';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteDressResource,
  exportDressResource,
  getDressResourcePage,
} from '#/api/wedding/dressresource';

import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
import QRPreviewModal from './modules/qr-preview-modal.vue';
import GlobalThemeSettings from './modules/global-theme-settings.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [QRPreviewModalComponent, qrPreviewModalApi] = useVbenModal({
  connectedComponent: QRPreviewModal,
  destroyOnClose: true,
});

const [GlobalThemeSettingsComponent, globalThemeSettingsApi] = useVbenModal({
  connectedComponent: GlobalThemeSettings,
  destroyOnClose: true,
});

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 创建婚纱资源 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 编辑婚纱资源 */
function handleEdit(row: DressResourceApi.DressResource) {
  formModalApi.setData(row).open();
}

/** 删除婚纱资源 */
async function handleDelete(row: DressResourceApi.DressResource) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    key: 'action_key_msg',
  });
  try {
    await deleteDressResource(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 导出表格 */
async function handleExport() {
  const data = await exportDressResource(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: '婚纱资源.xls', source: data });
}

/** 生成扫码预览 */
function handleQRPreview(row: DressResourceApi.DressResource) {
  qrPreviewModalApi.setData(row).open();
}

/** 生成婚纱展示主页二维码 */
function handleGalleryQR() {
  // 生成婚纱展示主页的二维码
  qrPreviewModalApi.setData({ isGallery: true } as any).open();
}

/** 打开全局主题设置 */
function handleGlobalThemeSettings() {
  globalThemeSettingsApi.open();
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getDressResourcePage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<DressResourceApi.DressResource>,
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="onRefresh" />
    <QRPreviewModalComponent />
    <GlobalThemeSettingsComponent />

    <Grid table-title="婚纱列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', ['婚纱款式']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['wedding:dress-resource:export'],
              onClick: handleExport,
            },
            {
              label: '婚纱展示主页',
              type: 'default',
              icon: 'lucide:qr-code',
              onClick: handleGalleryQR,
            },
            {
              label: '全局主题设置',
              type: 'default',
              icon: 'lucide:palette',
              onClick: handleGlobalThemeSettings,
            },
          ]"
        />
      </template>

      <template #images="{ row }">
        <div v-if="row.images && row.images.length > 0">
          <Image.PreviewGroup>
            <Image
              :src="row.images[0]"
              :width="60"
              :height="60"
              class="rounded object-cover cursor-pointer"
            />
            <!-- 隐藏的图片用于预览组 -->
            <Image
              v-for="(img, index) in row.images.slice(1)"
              :key="index"
              :src="img"
              :style="{ display: 'none' }"
            />
          </Image.PreviewGroup>
          <div v-if="row.images.length > 1" class="text-xs text-gray-500 mt-1">
            共{{ row.images.length }}张
          </div>
        </div>
        <span v-else class="text-gray-400 text-xs">无图片</span>
      </template>

      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '扫码预览',
              type: 'link',
              icon: 'lucide:qr-code',
              onClick: handleQRPreview.bind(null, row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              // auth: ['wedding:dress-resource:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              // auth: ['wedding:dress-resource:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
